package cn.zcscloud.mall.service.impl;

import cn.zcscloud.mall.mbg.mapper.PmsProductAttributeMapper;
import cn.zcscloud.mall.mbg.mapper.SmsCouponMapper;
import cn.zcscloud.mall.mbg.model.PmsProductAttribute;
import cn.zcscloud.mall.mbg.model.SmsCoupon;
import cn.zcscloud.mall.mbg.model.SmsCouponProductCategoryRelation;
import cn.zcscloud.mall.mbg.model.SmsCouponProductRelation;
import cn.zcscloud.mall.service.PmsProductAttributeService;
import cn.zcscloud.mall.service.SmsCouponProductCategoryRelationService;
import cn.zcscloud.mall.service.SmsCouponProductRelationService;
import cn.zcscloud.mall.service.SmsCouponService;
import cn.zcscloud.mall.vo.SmsCouponParamVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SmsCouponServiceImpl extends ServiceImpl<SmsCouponMapper, SmsCoupon> implements SmsCouponService {
    @Autowired
    private SmsCouponProductCategoryRelationService productCategoryRelationService;
    @Autowired
    private SmsCouponProductRelationService productRelationService;
    @Autowired
    private SmsCouponMapper smsCouponMapper;
    @Override
    public Boolean create(SmsCouponParamVo couponParam) {
        couponParam.setCount(couponParam.getPublishCount()); //剩余数量为发行数量
        couponParam.setUseCount(0); //初始化使用数量为0
        couponParam.setReceiveCount(0); //初始化领取数量为0
        //将优惠券插入券表
        boolean save = this.save(couponParam);
        //插入优惠券和商品关系表
        if(couponParam.getUseType().equals(2)){
            for (SmsCouponProductRelation productRelation : couponParam.getProductRelationList()) {
                productRelation.setCouponId(couponParam.getId());
            }
            productRelationService.saveBatch(couponParam.getProductRelationList());
        }
        //插入优惠券和商品分类关系表
        if (couponParam.getUseType().equals(1)){
            for (SmsCouponProductCategoryRelation couponProductCategoryRelation : couponParam.getProductCategoryRelationList()) {
                couponProductCategoryRelation.setCouponId(couponParam.getId());
            }
            productCategoryRelationService.saveBatch(couponParam.getProductCategoryRelationList());
        }
        return save;
    }

    @Override
    public SmsCouponParamVo getItem(Long id) {

        return smsCouponMapper.getItem(id);
    }

    @Override
    public Boolean deleteById(Long id) {
        //删除商品关联
        HashMap<String, Object> map = new HashMap<>();
        map.put("coupon_id",id);
        productRelationService.removeByMap(map);
        //删除分类关联
        productCategoryRelationService.removeByMap(map);
        //删除优惠券
        boolean b = this.removeById(id);
        return b;
    }
}
